package com.gin.no_gay_alliance.callback;

import androidx.annotation.NonNull;

import com.gin.common.utils.StrUtils;
import com.gin.jackson.utils.ObjectUtils;
import com.gin.nga.exception.NgaClientException;
import com.gin.nga.exception.NgaException;
import com.gin.no_gay_alliance.utils.MyHandler;

import java.io.IOException;
import java.util.Map;

import okhttp3.Call;

/**
 * 带handler的对接，自动发布toast提示
 *
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/9/7 14:10
 **/
public class HandlerRequestCallback<T> extends RequestCallback<T> {
    @NonNull
    private final MyHandler handler;

    public HandlerRequestCallback(@NonNull Callback<T> callback, @NonNull MyHandler handler) {
        super(callback);
        this.handler = handler;
    }

    @Override
    public void onFailure(@NonNull Call call, @NonNull IOException e) {
        handler.toast(e.getMessage());
        super.onFailure(call, e);
    }

    /**
     * 处理异常
     *
     * @param e 异常
     */
    @Override
    public void handleException(NgaException e) {
        if (e instanceof NgaClientException) {
            Map<Integer, String> reason = ((NgaClientException) e).getReason();
            String t0 = reason.get(0);
            String t1 = reason.get(1);

            if (!ObjectUtils.isEmpty(t0) && !StrUtils.isNumber(t0)) {
                handler.toast(t0);
            } else if (!ObjectUtils.isEmpty(t1) && !StrUtils.isNumber(t1)) {
                handler.toast(t1);
            }
        }
        super.handleException(e);
    }
}
